<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!--  分包预算转总价审批 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      class="updateTotalPriceApproval"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel == 0 ? {} : rules"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="基本信息"></title-name>
          <custom-form
            :formList="formList"
            :form="form"
            :is-emit="false"
            :editModel="editModel == 0 ? '' : ''"
            @select="selectOrg"
          >
            <!-- 附件资料 -->
            <template #fileList>
              <template v-if="editModel != 0">
                <l-table
                  businessCode="FACE15"
                  :uploadArrys.sync="form.fileList"
                ></l-table>
              </template>
              <file-link
                v-else
                :fileList="form.fileList"
                style="margin-top: -3px"
              ></file-link>
            </template>
            <template v-slot:table>
              <a-form-model-item
                class="mb20"
                label=" "
                :colon="false"
              >
                <a-table
                  ref="formTable"
                  class="updateTotalPriceApproval-table"
                  bordered
                  :columns="columns"
                  :data-source="form.budgetList"
                  :pagination="false"
                >
                  <template
                    v-for="col in ['projectFeeInfo', 'notIncludeRate', 'rate', 'includeRate', 'remark']"
                    :slot="col"
                    slot-scope="text, record,index"
                  >
                    <div
                      :key="col"
                      class="form-item"
                    >
                      <template>
                        <template>
                          <a-input
                            v-if="col === 'remark'"
                            v-model="record[col]"
                            :disabled="editModel == 0"
                            placeholder="请输入"
                          ></a-input>
                          <a-input-number
                            v-else-if="col === 'includeRate'"
                            v-model="record[col]"
                            placeholder="计算"
                            :precision="2"
                            disabled
                          ></a-input-number>
                          <a-input-number
                            v-else-if="col === 'notIncludeRate' || col === 'rate'"
                            v-model="record[col]"
                            :precision="2"
                            :disabled="editModel == 0 || index!==2"
                            :placeholder="(editModel == 0 || index!==2)?'自动带出':'请输入'"
                          >
                          </a-input-number>
                          <span v-else>{{record[col]}}</span>
                        </template>
                      </template>
                    </div>
                  </template>
                </a-table>
              </a-form-model-item>
            </template>
          </custom-form>
        </a-card>
      </a-spin>
    </a-form-model>
     
    <!-- 页脚操作栏 -->
    <div
      class="btn_box page-btn-right-top"
      v-if="editModel != 0 && !isConsultation"
    >
      <a-button
        class="button_right"
        v-if="form.status == 'REJECTED'"
        type="primary"
        :loading="loadingBtn.REJECTED"
        @click="handleSubmit('REJECTED')"
      >保存</a-button>
      <span v-else>
        <a-button
          v-if="this.editModel != 3"
          class="button_right"
          type="primary"
          :loading="loadingBtn.DRAFT"
          @click="handleSubmit('DRAFT')"
        >保存草稿</a-button>
      </span>
      <a-button
        class="button_right"
        type="primary"
        :loading="loadingBtn.SUBMITTED"
        @click="handleSubmit('SUBMITTED')"
      >提交</a-button>
      <a-button @click="handleActiveClose">关闭</a-button>
    </div>
    <!-- v-if="!isAudit && form.auditStatus*1 === 3" -->
    <div
      class="btn_box page-btn-right-top"
      v-else-if="!isConsultation"
    >
      <BasePrintButton
        class="button_right"
        v-if="!isAudit && auditStatus==='PAST'"
        type="primary"
        :beforePrintFn="print"
      />
      <a-button @click="handleActiveClose">关闭</a-button>
    </div>
     <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { updateBudget, getBudgetDetail, budegtPrint } from '@/api/businessAffairs/totalPriceApproval' // api
import { getList, findList } from '@/api/businessAffairs/subcontractingBudget' // 分包施工图预算 api
import subcontract from '@/api/legal/branchContract/subcontract'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectSubcontractorCode from '@/components/Select/SelectSubcontractorCode' // 分包商
import SelectProject from '@/components/Select/SelectProject' // 分公司
// import SelectSubcontractor from '@/components/Select/SelectSubcontractor' // 分包商
const columns = [
  { title: '项目/金额', dataIndex: 'projectFeeInfo', align: 'center', scopedSlots: { customRender: 'projectFeeInfo' } },
  { title: '1.不含增值税(万元)', dataIndex: 'notIncludeRate', align: 'center', scopedSlots: { customRender: 'notIncludeRate' } },
  { title: '2.增值税(万元)', dataIndex: 'rate', align: 'center', scopedSlots: { customRender: 'rate' } },
  { title: '含增值税(万元)(1+2)', dataIndex: 'includeRate', align: 'center', scopedSlots: { customRender: 'includeRate' } },
  { title: '备注', dataIndex: 'remark', align: 'center', scopedSlots: { customRender: 'remark' } }
]
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectProject,
    BSelect,
    SelectSubCompany,
    SelectSubcontractorCode
  },
  data() {
    this.columns = columns
    return {
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增;
      form: {
        projectId: null,
        fileList: [],
        designId: null,
        budgetList: [
          { projectFeeInfo: '分包合同额', notIncludeRate: null, rate: null, includeRate: '', remark: '' },
          { projectFeeInfo: '分包施工图预算价款', notIncludeRate: null, rate: null, includeRate: '', remark: '' },
          { projectFeeInfo: '预算转总价价款', notIncludeRate: null, rate: null, includeRate: null, remark: '' }
        ]
      }, // 表单
      findCountQueryParam: {
        pageNo: 1,
        pageSize: 10000,
        query: {}
      },
      queryParamBudget: {
        pageNo: 1,
        pageSize: 10000,
        branchComId: null,
        projectId: null,
        subContractorId: null,
        contractName: null
      }, //分包施工图预算查询参数
      id: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false,
        FILE: false
      },
      rules: {
        projectToTotal: [{ required: true, message: '请输入项目分包转总价指标', trigger: 'blur' }],
        contractId: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
        supplyInfo: [{ required: true, message: '请输入甲供材情况', trigger: 'blur' }],
        compileInfo: [{ required: true, message: '请输入编制说明', trigger: 'blur' }],
        subcontractorScc: [{ required: true, message: '请选择分包单位名称' }]
      }, // 校验规则
      init: false, // 初始化控件
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    },
    'form.budgetList': {
      //监听数组变化
      handler(val) {
        if (val) {
          if (!this.isEmpty(val[2].notIncludeRate) && !this.isEmpty(val[2].rate)) {
            this.form.budgetList[2].includeRate = val[2].notIncludeRate * 1 + val[2].rate * 1
          }
        }
      },
      deep: true
    }
  },
  created() {},
  async mounted() {
    this.$route.meta.title = ['分包预算转总价审批  查看', '分包预算转总价审批 编辑', '分包预算转总价审批 新增'][this.editModel]
    if (this.editModel != 2) {
      await this.getDetailData()
    } else {
      this.form.projectId = this.$userInfo().currentPost.projectId;
      this.$nextTick(() => {
        // 默认映射联系人为登陆人
        this.form.fillName = this.$userInfo().name
        this.init = true
      })
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('comm_subcontracting_budget')
  },
  computed: {
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst: true,
          isNeedAuth:true ,
          checkStrictly: true,
          disabled: true,
          viewName: "viewName",
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchCompanyId',
        //   label: '所属分公司',
        //   placeholder: '自动带出',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   placeholder: '自动带出',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchCompanyId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   }
        // },
        {
          keyName: 'projectToTotal',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '项目分包转总价指标'
        },
        {
          keyName: 'subOrgName',
          type: 'a-input',
          disabled: true,
          label: '分包商名称',
          placeholder: '自动带出',
          hidden: this.editModel !== 0
        },
        {
          type: SelectSubcontractorCode,
          keyName: 'subcontractorScc',
          label: '分包单位名称',
          disabled: this.editModel == 0,
          hidden: this.editModel == 0,
          attrs: {
            keyValue: 'projectId',
            isClear: this.editModel == 2,
            isEdit: this.editModel != 2,
            form: this.form
          },
          selectChange: (e, b) => {
            this.$set(this.form, 'subOrgName', e?.name)

            this.$set(this.form, 'contractCode', undefined)
            this.$set(this.form, 'contractName', undefined)
            this.$set(this.form, 'contractId', undefined)
            this.$set(this.form, 'wayOfSub', undefined)
            this.$set(this.form.budgetList[0], 'notIncludeRate', undefined)
            this.$set(this.form.budgetList[0], 'rate', undefined)
            this.$set(this.form.budgetList[0], 'includeRate', undefined)
          }
        },
        {
          keyName: 'contractName',
          type: 'a-input',
          disabled: true,
          label: '合同名称',
          placeholder: '自动带出',
          hidden: this.editModel !== 0
        },
        {
          keyName: 'contractId',
          type: BSelect,
          disabled: this.editModel == 0,
          hidden: this.editModel == 0,
          label: '合同名称',
          attrs: {
            form: this.form,
            keyValue: 'subOrgName',
            request: this.getNameList
          },
          selectChange: (e) => {
            //切换名称获取数据
            this.$set(this.form, 'contractName', e?.contractName)
            this.form.contractCode = e.contractCode
            this.form.wayOfSub = e.contractTypeStr
            this.form.budgetList[0].notIncludeRate = e?.contractExTaxAmount / 10000
            this.form.budgetList[0].rate = e?.contractRate / 10000
            this.form.budgetList[0].includeRate = e?.contractInTaxAmount / 10000
            this.getSubcontractBudgetDetail(e.contractName)
          }
        },
        {
          keyName: 'contractCode',
          type: 'a-input',
          disabled: true,
          label: '合同编号',
          placeholder: '自动带出'
        },
        {
          keyName: 'wayOfSub',
          type: 'a-input',
          disabled: true,
          label: '分包方式',
          placeholder: '自动带出'
        },
        {
          keyName: 'kgTime',
          type: 'a-input',
          disabled: true,
          label: '开完工日期',
          placeholder: '自动带出'
        },
        {
          keyName: 'completeDate',
          type: 'a-input',
          disabled: true,
          label: '编制完成日期',
          placeholder: '自动带出'
        },
        {
          keyName: 'editor',
          type: 'a-input',
          disabled: true,
          label: '编制人',
          placeholder: '自动带出'
        },
        {
          slot: true,
          customItemSlot: true,
          keyName: 'table',
          span: 24
        },
        {
          keyName: 'coverage',
          type: 'a-textarea',
          disabled: true,
          label: '承包范围',
          span: 24,
          placeholder: '自动带出'
        },
        {
          keyName: 'supplyInfo',
          type: 'BaseTextarea',
          disabled: this.editModel == 0,
          label: '甲供材情况',
          span: 24
        },
        {
          keyName: 'compileInfo',
          type: 'BaseTextarea',
          disabled: this.editModel == 0,
          label: '编制说明',
          span: 24
        },
        {
          slot: true,
          keyName: 'fileList',
          disabled: this.editModel == 0,
          label: '附件上传',
          span: 24
        }
      ]
    }
  },
  methods: {
    //选择单位
    selectOrg(val) {
        if (val && val.length) {
            this.form.branchComId = val[val.length - 2].orgId;
            this.form.project = { key: val[val.length - 1].projectId, lable: val[val.length - 1].projectName };
        }
    },
    async getSubcontractBudgetDetail(e) {
      if (e) {
        this.queryParamBudget.branchComId = this.form.branchCompanyId
        this.queryParamBudget.projectId = this.form.projectId
        this.queryParamBudget.subContractorId = this.form.SelectSubcontractor
        this.queryParamBudget.contractName = e
        getList(this.queryParamBudget).then(async (res) => {
          if (res.code == 200 && res.data?.length > 0) {
            let findData = await findList({ id: res.data[0].id })
            if (findData.code == 200) {
              let reqData = findData.data
              let kgTime = `${reqData.workStartDate || ''} ~ ${reqData.workEndDate || ''}`
              this.$set(this.form, 'kgTime', kgTime)
              this.$set(this.form, 'startDate', reqData.workStartDate)
              this.$set(this.form, 'endDate', reqData.workEndDate)
              this.$set(this.form, 'completeDate', reqData?.completionDate)
              this.$set(this.form, 'editor', reqData?.editorName)
              this.$set(this.form.budgetList[1], 'notIncludeRate', reqData?.excludeTaxAmount / 10000)
              this.$set(this.form.budgetList[1], 'rate', reqData?.valueAddedTax / 10000)
              this.$set(this.form.budgetList[1], 'includeRate', (reqData?.taxAmount / 10000).toFixed(2))
              this.$set(this.form, 'coverage', reqData?.contractScope)
            }
          } else {
            //没有取到值清空
            this.$set(this.form, 'kgTime', null)
            this.$set(this.form, 'bzTime', null)
            this.$set(this.form, 'editor', null)
            this.$set(this.form.budgetList[1], 'notIncludeRate', null)
            this.$set(this.form.budgetList[1], 'rate', null)
            this.$set(this.form.budgetList[1], 'includeRate', null)
            this.$set(this.form, 'coverage', null)
          }
        })
      }
    },
    // 打印
    print() {
      return budegtPrint({ id: this.id }).then((res) => {
        return res.data.content
      })
    },
    //获取分包商下面的合同
    async getNameList() {
      if (this.form.projectId && this.form.subOrgName) {
        let req = {
          projectId: this.form.projectId,
          subSupplyCompany: this.form.subOrgName
        }
        // this.findCountQueryParam.query.subSupplyCompany = this.form.subcontractorName
        return subcontract
          .getSubContractByScc(req)
          .then((res) => {
            if (res.data?.length > 0) {
              res.data.map((item) => {
                item.name = item.contractName
                item.id = item.contractId
              })
            }
            return { code: 200, data: res.data }
          })
          .catch(() => {
            return { code: 200, data: [] }
          })
      }
      return { code: 200, data: [] }
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        }else {
          this.$message.warning('请填写完所有必填项信息')
        }
      })

      return flag
    },
    getDetailData() {
      // 不为添加时请求详情
      if (this.editModel != 2) {
        this.loading = true
        getBudgetDetail({ id: this.id })
          .then((res) => {
            this.loading = false
            res.data.projectId = res.data.projectId.toString()
            this.form = { ...this.form, ...res.data }
            let kgTime = ''
            if (this.form.startDate && this.form.endDate) {
              kgTime = `${this.form.startDate || ''} ~ ${this.form.endDate || ''}`
            }
            this.$set(this.form, 'kgTime', kgTime)
            this.$nextTick(() => {
              this.init = true
            })
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.$nextTick(() => {
          this.init = true
        })
      }
    },
    isEmpty(obj) {
      if ((typeof obj == 'undefined' || obj == null || obj == '') && obj != 0) {
        return true
      } else {
        return false
      }
    },
    /**
     * 提交表单
     */
    handleSubmit(status) {
      this.setProcessConfig = null;
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
      let form = this.$clone(this.form)
      if (status == 'SUBMITTED' && form.budgetList.length > 0) {
        if (this.isEmpty(form.budgetList[2].notIncludeRate) || this.isEmpty(form.budgetList[2].rate)) {
          this.$message.warning('请完善表格数据')
          return
        }
      }
      this.loading = true
      this.loadingBtn[status] = true
      if (status != 'REJECTED') {
        form.auditStatus = status == 'SUBMITTED' ? 1 : 0
      } else {
        form.auditStatus = 5
      }
      let api = updateBudget
      this.submitApprovalConfirm(status =='SUBMITTED'?this.processConfig:6, (flag)=>{
        if(!flag) {
          this.loading = false
          this.loadingBtn[status] = false
          return
        }
      api(form)
        .then((res) => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          if(status =='SUBMITTED') {
            //提交时，返回id
                this.businessId = res.data || this.id;
                this.setProcessConfig = this.processConfig;
                return
            }else{
              this.$multiTab.close()
              }
        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
